#!/usr/bin/env python
import socket
import threading
import time

from http_parser.http import HttpStream
from http_parser.reader import SocketReader

# "Connection: Keep-Alive\r\r" \
# "Content-Length: %d\r\n" \
# "Date: Wed, 10 Aug 2016 13:17:18 GMT\r\n" \
# "Server: Apache\r\n" \
responseHeader="HTTP/1.1 200 OK\r\n" \
    "Content-Type: text/html\r\n" \
    "\r\n"

responseBody="""<!DOCTYPE html>
<html lang="en">
<body>Hello World</body>
</html>
"""

port = 8082
port_client = port
def runServer():
    ip_port = ('127.0.0.1', port)
    server = socket.socket()
    server.bind(ip_port)
    server.listen(5)
    print("Server is running...")
    while True:
        # 阻塞
        conn, addr = server.accept()
        # 获取客户端请求数据
        data = conn.recv(1024)
        # 打印接受数据 注：当浏览器访问的时候，接受的数据的浏览器的信息等。
        print(data)
        # 向对方发送数据
        responseBodyBinary = responseBody.encode('utf-8')
        # resPonseHeaderBinary = (responseHeader % len(responseBodyBinary)).encode('ascii')
        resPonseHeaderBinary = responseHeader.encode('ascii')
        print("Server: Response body length = " + str(len(responseBodyBinary)))
        print("Server: Response header length = " + str(len(resPonseHeaderBinary)))
        responseBinary = resPonseHeaderBinary + responseBodyBinary
        print("Response " + str(responseBinary))
        conn.send(responseBinary)
        # 关闭链接
        conn.close()


def runClient():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('127.0.0.1', port_client))
        s.send(b"GET / HTTP/1.1\r\n127.0.0.1:%d\r\n\r\n" % (port_client))
        r = SocketReader(s)
        p = HttpStream(r)
        print("Client Header: " + str(p.headers()))
        print("Client Body: " + p.body_file().read().decode('utf-8'))
    finally:
        s.close()


def main():
    serverThread = threading.Thread(target=runServer)
    serverThread.start()
    time.sleep(1)
    clientThread = threading.Thread(target=runClient)
    clientThread.start()
    serverThread.join()



if __name__ == "__main__":
    main()
